import json
import token

import requests

from common.utils import enconde_bs64, decode64_str

requests.packages.urllib3.disable_warnings()
headers = {"Content-Type": "application/json"}
# https://192.168.10.146:8081
# https://47.102.214.108
# https://192.168.10.233:8081
ip = 'https://192.168.10.146:8081'
session = requests.Session()


def send_post(url, data, type=None):
    """
    发送请求,有cookie和无cookie的情况,有cookie的进行有cookie的请求,没有就进入没有cookie的请求
    :param url:
    :param data:
    :param cookie:
    :return:
    """
    if type == 'files':
        res = session.post(url, files=data, verify=False, headers=headers)
        return res
    # elif cookie is None:
    #     _ = enconde_bs64(data)
    #     res = session.post(url, data=_, verify=False, headers=headers)
    #     return res
    else:
        # cookies = {"hearingaid_user": cookie}
        _ = enconde_bs64(data)
        res = session.post(url, data=_, verify=False, headers=headers)
        return res

def get_verifycode(authenticationMethod, Type, email=None, phoneNumber=None, phoneCountry=None) -> tuple:
    """接口1 获取短信验证码,可以进行多个业务的短信验证码
    | authenticationMethod | Enum | EMAIL | 是 |验证方式。<br>EMAIL：邮箱验证、<br>PHONE_SHORT_MESSAGE：手机短信验证 |
    | verificationCodeType | Integer | 2   | 是 | 验证码类型。1:登录、2:注册、3:修改密码、4:平台启用用户|
    | email | String | 9658965@qq.com | 否 | 邮箱地址(验证方式为“邮箱验证”时必填)<br>最大长度：50|
    | phoneNumber | Integer | 18536965236   | 否 | 手机号(验证方式为“手机短信验证”时必填)<br>长度：4-12位|
    | phoneCountry | Enum | CN   | 否 | 手机号归属国家(验证方式为“手机短信验证”时必填)<br>CN：中国<br>OTHER：其它|
    :return:验证码,token
    """
    url = ip + '/microServiceUser/responseEncode/requestDecode/getVerificationCode'
    data = {
        "authenticationMethod": authenticationMethod,
        "verificationCodeType": Type,
        "email": email,
        "phoneNumber": phoneNumber,
        "phoneCountry": phoneCountry
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['data'] is None:
        print('=============调用短信息接口失败, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    dic = json.loads(decode64_str(res.json()['data']))
    return dic['validateCode'],dic['token']

def register(account, password, notice, name=None, gender=None, sourceplatform='RETONE_FIT') -> None:
    """
    注册需要获取验证码带cookie一致时,才能注册
    | account   | String  | 18269369869 | 是 |账号。<br>验证规则：只允许英文、数字、特殊字符_-+~!@#$%^&*，且4-30个字符，非纯数字 |
    | password  | String | c123456 | 是 | 密码。<br>验证规则：只允许英文、数字、特殊字符_-+~!@#$%^&*且6-30个字符，必须同时包含数字和字母|
    | notice  | String | 842158    | 是 | 验证码|
    | name  | String | 张三    | 否 | 姓名<br>最大长度：20|
    | gender  | Enum | MALE    | 否 | 性别。MALE：男、FEMALE：女|
    | sourcePlatform  | Enum | RETONE_FIT | 是 | 注册来源平台。<br>RETONE_FIT：RetoneFit<br>BLUETOOTH_HA：BluetoothHA<br>WECHAT_HA：WeChatHA|
    :return:
    """

    url = ip + '/microServiceUser/responseEncode/requestDecode/register'
    data = {
        "account": account,
        "password": password,
        "notice": notice,
        "name": name,
        "gender": gender,
        "sourcePlatform": sourceplatform
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['data'] is None:
        print('============= 注册 接口, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        print(f'{account}注册成功')

def login(type, account=None, password=None, notice=None, sourceplatform=None) -> token:
    """
    登录接口,登录成功返回的是登录成功后的cookie, 提取
    | loginObject | String  | Evan | 否 |登录对象。可以是账号、手机号、邮箱中的任意一种（登录类型为密码登录时必填） |
    | password  | String | 123456    | 否 | 密码。（登录类型为密码登录时必填）|
    | type  | Integer | 0    | 是 | 登录类型。0:密码登录、1：验证码登录|
    | notice  | Integer | 123456    | 否 | 验证码。（登录类型为验证码登录时必填）|
    | sourcePlatform  | Enum | RETONE_FIT | 是 | 登录来源平台。<br>RETONE_FIT：RetoneFit<br>BLUETOOTH_HA：BluetoothHA<br>WECHAT_HA：WeChatHA|
    :return:返回cookie
    """
    url = ip + '/microServiceUser/responseEncode/requestDecode/login'
    data = {
        "type": type,
        "sourcePlatform": sourceplatform,
        "loginObject": account,
        "password": password,
        "notice": notice
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['data'] is None:
        print('============= 登录 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        print(f'登录成功:{account},登录平台{sourceplatform}')
        dic = json.loads(decode64_str(res.json()['data']))
        return dic['token']
        # return res

def logoff() -> None:
    """
    退出登录,传入cookie退出,无返回
    :param cookie:
    :return:
    """
    url = ip + '/microServiceUser/responseEncode/requestDecode/logOff'
    # cookies = {"hearingaid_user": cookie}
    # res = requests.post(url, cookies=cookies, verify=False, headers=headers)
    res = session.post(url, verify=False, headers=headers)
    if res.status_code != 200 or res.json()['result'] is None:
        print('============= 退出 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        print(f'退出成功')

def passwordforget(password, notice) -> None:
    """忘记密码,通过验证码修改密码
    | password  | String | 123456    | 是 | 密码。<br>验证规则：只允许英文、数字、特殊字符_-+~!@#$%^&*且6-30个字符，必须同时包含数字和字母|
    | notice  | Integer | 720720    | 是 | 验证码。|
    :return:
    """
    url = ip + '/microServiceUser/responseEncode/requestDecode/passwordForget'
    data = {
        "password": password,
        "notice": notice
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['result'] is None:
        print('============= 登录 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        print(f'修改密码成功')

def modifypersoninfo(account=None, name=None, gender=None) -> None:
    """
    | account   | String  | chen123  |   否   | 账号。<br>验证规则：只允许英文、数字、特殊字符_-+~!@#$%^&*，且4-30个字符，非纯数字 |
    | name      | String  | 张三  |   否   |姓名<br>最大长度：20 |
    | gender   | GenderEnum | MALE |   否  | 性别。MALE：男、FEMALE：女、null：空 |
    :return:
    """
    url = ip + '/microServiceUser/needAppUserAuth/responseEncode/requestDecode/modifyPersonInfo'
    data = {
        "account": account,
        "name": name,
        "gender": gender
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['result'] != '200':
        print('============= 修改个人信息 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        print(f'修改信息成功')

def modifypassword(oldPassword, newPassword) -> None:
    """新旧密码
    | oldPassword | String  | 123456 |  是  | 旧密码 |
    | newPassword | String  | 000000 |  是  | 新密码 <br>验证规则：只允许英文、数字、特殊字符_-+~!@#$%^&*，且6-30个字符，必须同时包含数字和字母 |
    :param cookie:
    :param oldPassword:
    :param newPassword:
    :return:
    """
    url = ip + '/microServiceUser/needAppUserAuth/responseEncode/requestDecode/modifyPersonPassword'
    data = {
        "oldPassword": oldPassword,
        "newPassword": newPassword
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['result'] != '200':
        print('============= 修改密码 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        print(f'修改密码成功,新密码:{data["newPassword"]}')

def getLoginState(cookie=None) -> bool:
    """
    :param cookie:
    :return: Ture hou False
    """
    url = ip + '/microServiceUser/responseEncode/requestDecode/getLoginState'
    cookies = {"hearingaid_user": cookie}
    res = requests.post(url, cookies=cookies, headers=headers, verify=False)
    if res.status_code != 200 or res.json()['result'] != '200':
        print('============= 获取登录状态 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        dic = json.loads(decode64_str(res.json()['data']))
        print(f'APP登录状态:{dic["loginState"]}')
        return dic["loginState"]

def getUserLoginObjectState(account, phonecountry=None, sourceplatform=None) -> dict:
    """验证APP用户登录主体是否存在
    | loginObject | String | 18566965369 | 是 |登录对象。可以是账号、手机号、邮箱中的任意一种。 <br>账号验证规则：只允许英文、数字、特殊字符_-+~!@#$%^&*，且4-30个字符，非纯数字<br>手机号长度：4-12位<br>邮箱最大长度：50|
    | phoneCountry | Enum | CN   | 否 | 手机号归属国家(用户登录主体是手机号时必填时必填)<br>CN：中国<br>OTHER：其它|
    | sourcePlatform  | Enum | RETONE_FIT | 是 | 验证来源平台。<br>RETONE_FIT：RetoneFit<br>BLUETOOTH_HA：BluetoothHA<br>WECHAT_HA：WeChatHA|
    :param cookie:
    :return:
    | loginObjectState  | Boolean  | true | 用户登录主体是否存在。true:已存在、false:不存在 |
    | userCancellation  | Boolean  | true | 用户是否是注销状态（只有loginObjectState为true时才有值）。true:注销、false:非注销 |
    """
    url = ip + '/microServiceUser/responseEncode/requestDecode/getUserLoginObjectState'
    data = {
        "loginObject": account,
        "phoneCountry": phonecountry,
        "sourcePlatform": sourceplatform
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['result'] != '200':
        print('============= APP用户登录主体是否存在 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        dic = json.loads(decode64_str(res.json()['data']))
        print(f'用户登录主体是否存在:{dic["loginObjectState"]}, 用户是否是注销状态:{dic["userCancellation"]}')
        return dic

def uploadUserProfile(image_path) -> None:
    """
    上传用户头像
    :param cookie:
    :param files:
    :return:
    """
    url = ip + '/microServiceUser/needAppUserAuth/responseEncode/uploadUserProfile'
    headers = {
        "Content-Type": "multipart/form-data",
    }
    # cookies = {"hearingaid_user": cookie}
    with open(image_path, mode='rb') as image:
        image_rb = image.read()
    files = {'file': image_rb}
    res = send_post(url, data=files, type='files')
    if res.status_code != 200 or res.json()['data'] is None:
        print('============= 上传文件 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        dic = json.loads(decode64_str(res.json()['data']))
        print(f'文件路径:{dic["filePath"]}, 文件展示路径:{dic["filePathShow"]}')
        return dic

def getUsedBindingObjectCode(type) -> str:
    """获取旧绑定对象的验证码
    | authenticationMethod | Enum | EMAIL | 是 |验证方式。<br>EMAIL：邮箱验证、<br>PHONE_SHORT_MESSAGE：手机短信验证 |
    :param cookie:
    :param type:
    :return:
    """
    url = ip + '/microServiceUser/needAppUserAuth/responseEncode/requestDecode/getUsedBindingObjectCode'
    data = {"authenticationMethod": type}
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['data'] is None:
        print('============= 获取旧绑定对象的验证码 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        dic = json.loads(decode64_str(res.json()['data']))
        print(f"返回旧绑定对象的验证码:{dic['validateCode']}")
        return dic['validateCode']

def getNewBindingObjectCode(type, account, phonecountry=None) -> str:
    """重新绑定到新的账户上
    | authenticationMethod | Enum | EMAIL | 是 |验证方式。<br>EMAIL：邮箱验证、<br>PHONE_SHORT_MESSAGE：手机短信验证 |
    | bindingObject | String | 9658965@qq.com | 是 | 绑定对象（手机号或者邮箱）<br>手机号长度：4-12位<br>邮箱最大长度：50个字符|
    | phoneCountry | Enum | CN   | 否 | 手机号归属国家(验证方式为“手机短信验证”时必填)<br>CN：中国<br>OTHER：其它|
    :return:
    """
    url = ip + '/microServiceUser/needAppUserAuth/responseEncode/requestDecode/getNewBindingObjectCode'
    data = {
        "authenticationMethod": type,
        "bindingObject": account,
        "phoneCountry": phonecountry
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['data'] is None:
        print('============= 重新绑定到新的账户上 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        dic = json.loads(decode64_str(res.json()['data']))
        print(f"重新绑定到新的账户上验证码:{dic['validateCode']}")
        return dic['validateCode']

def modifyBindingInfo(oldNotice, newNotice) -> None:
    """
    修改用户绑定
    | usedNotice | String | 016022 | 是 | 旧绑定验证码 |
    | newNotice  | String | 662022 | 是 | 新绑定验证码)|
    :return:
    """
    url = ip + '/microServiceUser/needAppUserAuth/responseEncode/requestDecode/modifyBindingInfo'
    if len(str(oldNotice)) != 6 or len(str(newNotice)) !=6:
        print("输入的验证码有误")
        return False
    data= {
        "usedNotice": oldNotice,
        "newNotice": newNotice
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['result'] is None:
        print('============= 修改绑定的验证码 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        print('修改绑定成功')

def getCurrentUserDeleteCode(type) -> str:
    """
    获取当前用户的注销的验证码,返回验证码
    | authenticationMethod | Enum | EMAIL | 是 |验证方式。<br>EMAIL：邮箱验证、<br>PHONE_SHORT_MESSAGE：手机短信验证 |
    :return:
    """
    url = ip + '/microServiceUser/needAppUserAuth/responseEncode/requestDecode/getCurrentUserDeleteCode'
    data = {
        "authenticationMethod": type
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['result'] is None:
        print('============= 获取当前用户的注销的验证码 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        dic = json.loads(decode64_str(res.json()['data']))
        print(f"返回的注销验证码:{dic['validateCode']}")
        return dic['validateCode']

def deleteCurrentUser(notice) -> bool:
    """
    根据验证码注销当前用户
    | notice | String | 016022 | 是 | 验证码 |
    :return:
    """
    url = ip + '/microServiceUser/needAppUserAuth/responseEncode/requestDecode/deleteCurrentUser'
    data = {"notice": notice}
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['result'] is None:
        print('============= 根据验证码注销当前用户 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
        # return False
    else:
        print('注销成功!!')
        # return True

def checkValidateCode(type, notice) -> None:
    """
    验证对应类型的验证码是否正确
    | notice  | Integer | 720720    | 是 | 验证码 |
    | validateCodeType  | Enum | MOBILE_PASSWORD_MODIFY  | 是 | 验证码类型：MOBILE_PASSWORD_MODIFY、MOBILE_REGISTER |
    :param type:
    :return:
    """
    url = ip + '/microServiceUser/responseEncode/requestDecode/checkValidateCode'
    data = {"notice": notice, "validateCodeType": type}
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['result'] is None:
        print('============= 根据验证码注销当前用户 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        # dic = json.loads(decode64_str(res.json()['data']))
        print(f"返回验证真假")

def platformUserEnable(notice, platform) -> None:
    """
    添加其他平台的使用
    | notice  | Integer | 123456    | 是 | 验证码。|
    | platform  | Enum | RETONE_FIT | 是 | 启用平台。<br>RETONE_FIT：RetoneFit<br>BLUETOOTH_HA：BluetoothHA<br>WECHAT_HA：WeChatHA|
    :return:
    """
    url = ip + '/microServiceUser/responseEncode/requestDecode/platformUserEnable'
    data = {
        "notice": notice,
        "platform": platform
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['result'] is None:
        print('============= 添加其他平台的使用 接口错误, 请检查================')
        print(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        # dic = json.loads(decode64_str(res.json()['data']))
        print(f"平台开启成功")

if __name__ == '__main__':

    # print(get_verifycode('EMAIL', 2, 'autotest@qq.com'))
    token = login(0,'username4','cc1234', sourceplatform='RETONE_FIT')
    print(token)
    # logoff()
    # modifypersoninfo('MmE2MmE0ZGUtNWU2MC00ZTI0LTg1NDctM2Y5MDI2MzQ4NWM2', name='autotest1000')
    # getLoginState('NDBiOTU2MWItM2E0MS00NDFhLWE4ZTgtY2QwYmE4OGZiYWRk')
    # print(getUserLoginObjectState('18850458953', 'CN', 'RETONE_FIT'))
    # files = r'C:\Users\Administrator\Pictures\R-C.jpg'
    # uploadUserProfile(files)
    # getUsedBindingObjectCode('NDBiOTU2MWItM2E0MS00NDFhLWE4ZTgtY2QwYmE4OGZiYWRk', '123')
    # getCurrentUserDeleteCode('Nzc0ZGNjMDktMjljNy00Y2ExLWExNzYtNDdhY2ZjOTJkM2Zi', 'EMAIL')
    # checkValidateCode('MOBILE_PASSWORD_MODIFY', '720720')
